package com.openvas.core.opvas;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

@Component
public class SSHLinux {
    @Value("${ssh.host}")
    private String host;
    @Value("${ssh.user}")
    private String user;
    @Value("${ssh.port}")
    private Integer port;
    @Value("${ssh.pwd}")
    private String pwd;

    public String exeCommand(String host, int port, String user, String password, String command) throws JSchException, IOException {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setConfig("StrictHostKeyChecking", "no");
        //    java.util.Properties config = new java.util.Properties();
        //   config.put("StrictHostKeyChecking", "no");
        session.setPassword(password);

        session.connect();

        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand(command);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        String result = new BufferedReader(new InputStreamReader(in))
                .lines().parallel().collect(Collectors.joining(System.lineSeparator()));
        //  String out = IOUtils.toString(in, "UTF-8");
        channelExec.disconnect();
        session.disconnect();

        return result;
    }


    /**
     * 这种方式无需使用公钥，秘钥，推荐
     * @param command
     * @return
     * @throws Exception
     */
    public String execSshCMD(String command) throws Exception {
        String res = exeCommand(host, port, user, pwd, command);
        return res;
    }


}

